'''
Created on Dec 4, 2010

@author: jackreilly
'''

from loadLibraries import getLibraries
import os
from sessions import Session
import templates as template
import logging
from jsReferences import getKeyReferenceDictionary, getServiceURLS

templateDir = os.path.join( '../../templates' )

def standardTemplateParameters( classType ):
    moreParams = {}
    moreParams['libraries'] = getLibraries(classType)
    if classType is 'main':
        moreParams['keyReference'] = getKeyReferenceDictionary()
        moreParams['serviceURLS'] = getServiceURLS()
    if classType is 'newstation':
        moreParams['serviceURLS'] = getServiceURLS()
    return moreParams

def appendExt(ext):
    return os.path.join(templateDir,ext)


def classTypeToFilePath(ct):
    if ct is 'main': return appendExt('homepage/main/index.htm' )
    if ct is 'whatis': return appendExt('homepage/whatis/index.htm' )
    if ct is 'newstation': return appendExt('homepage/newStation/index.htm' )
    if ct is 'stationRegister': return appendExt('homepage/newStation/stationRegister.htm' )
    if ct is 'registerExtension': return appendExt('extensionPages/extensionSuccess.htm')
    return None

def getFilePath(ct,tn):
    fp = appendExt(tn)
    if not os.path.isfile( fp ):
        if ct is None:
            ct = 'main'
        fp = classTypeToFilePath(ct)
    return fp
        
        
def addMoreParameters(params,ct,handler):
    params['path'] = handler.request.path

    for k, v in standardTemplateParameters( ct ).iteritems():
        params[k] = v

def renderTemplate( handler, tname = '', parameters = {}, classType = None ):
    
    filePath = getFilePath(classType, tname)
    addMoreParameters(parameters,classType,handler)
    logging.error(parameters)
    outputString = template.render( filePath, parameters, True, ( '../../templates/', ) )
    
    handler.response.headers["Content-Type"] = "text/html"
    handler.response.out.write( outputString )
